/*
 * <<
 *  Davinci
 *  ==
 *  Copyright (C) 2016 - 2019 EDP
 *  ==
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  >>
 *
 */

package com.cwf.metadatamanage.controller;

import com.alibaba.druid.util.StringUtils;
import com.cwf.metadatamanage.common.ResultMap;
import com.cwf.metadatamanage.consts.Constants;
import com.cwf.metadatamanage.model.dtos.*;
import com.cwf.metadatamanage.model.pojo.Source;
import com.cwf.metadatamanage.service.SourceService;
import com.cwf.metadatamanage.utils.BindingResultUtils;
import com.github.pagehelper.PageInfo;
import com.cwf.metadatamanage.model.dtos.*;
import com.cwf.metadatamanage.model.vo.ResultResponse;
import com.cwf.metadatamanage.model.vo.req.SourceReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@Api(value = "/数据源管理", tags = "数据源管理", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiResponses(@ApiResponse(code = 404, message = "source not found"))
@RestController
@RequestMapping(value = Constants.BASE_API_PATH + "/sources", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class SourceController extends BaseController {

    @Autowired
    private SourceService sourceService;

    /**
     * 获取系统支持jdbc数据源
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取系统支持jdbc数据源")
    @GetMapping("/getJdbcDatasources")
    public ResponseEntity<ResultResponse<List<DatasourceType>>> getJdbcDataSources(HttpServletRequest request) {
        List<DatasourceType> list = sourceService.getDatasources();
        return ResponseEntity.ok(new ResultResponse().success(list));
    }

    /**
     * 获取source列表
     *
     * @param sourceReq
     * @param request
     * @return
     */
    @ApiOperation(value = "获取source列表")
    @GetMapping("/getSources")
    public ResponseEntity<ResultResponse<PageInfo<Source>>> getSources(@RequestBody SourceReq sourceReq, HttpServletRequest request, BindingResult bindingResult) {
        PageInfo<Source> sourcePageInfo = sourceService.getSources(sourceReq);
        return ResponseEntity.ok(new ResultResponse().success(sourcePageInfo));
    }


    /**
     * 获取source信息
     *
     * @param sourceId
     * @param request
     * @return获取source信息
     */
    @ApiOperation(value = "获取source信息")
    @GetMapping("/getSourceDetail")
    public ResponseEntity<ResultResponse<Source>> getSourceDetail(@RequestParam Long sourceId,
                                                                  HttpServletRequest request) {
        if (invalidId(sourceId)) {
            ResultResponse resultResponse = new ResultResponse().fail(500, "Invalid sourceId");
            return ResponseEntity.status(resultResponse.getCode()).body(resultResponse);
        }
        Source sourceDetail = sourceService.getSourceDetail(sourceId);
        return ResponseEntity.ok(new ResultResponse().success(sourceDetail));
    }


    /**
     * 创建source
     *
     * @param source
     * @param bindingResult
     * @param request
     * @return
     */
    @ApiOperation(value = "创建source", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/createSource", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResultResponse> createSource(@Valid @RequestBody SourceCreate source,
                                                       @ApiIgnore BindingResult bindingResult,
                                                       HttpServletRequest request) {
        // 校验参数
        if (bindingResult.hasErrors()) {
            return BindingResultUtils.returnBindingResultError(bindingResult);
        }

        Source record = sourceService.createSource(source);
        return ResponseEntity.ok(new ResultResponse().success(record));
    }


    /**
     * 更新source
     *
     * @param source
     * @param bindingResult
     * @param request
     * @return
     */
    @ApiOperation(value = "更新source", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/updateSource", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResultResponse> updateSource(@Valid @RequestBody SourceInfo source,
                                                       @ApiIgnore BindingResult bindingResult,
                                                       HttpServletRequest request) {

        // 校验参数
        if (bindingResult.hasErrors()) {
            return BindingResultUtils.returnBindingResultError(bindingResult);
        }

        if (invalidId(source.getId())) {
            ResultResponse resultResponse = new ResultResponse().fail("Invalid source id");
            return ResponseEntity.status(resultResponse.getCode()).body(resultResponse);
        }

        Source updatedSource = this.sourceService.updateSource(source);
        return ResponseEntity.ok(new ResultResponse().success(updatedSource));
    }

    /**
     * 删除source
     *
     * @param sourceId
     * @param request
     * @return
     */
    @ApiOperation(value = "删除source")
    @PostMapping("/deleteSource")
    public ResponseEntity<ResultResponse> deleteSource(@RequestParam Long sourceId,
                                                       HttpServletRequest request) {

        if (invalidId(sourceId)) {
            ResultResponse resultResponse = new ResultResponse().fail("Invalid sourceId");
            return ResponseEntity.status(resultResponse.getCode()).body(resultResponse);
        }

        sourceService.deleteSource(sourceId);
        return ResponseEntity.ok(new ResultResponse().success());
    }


    /**
     * 测试连接
     *
     * @param sourceTest
     * @param bindingResult
     * @param request
     * @return
     */
    @ApiOperation(value = "test source", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/testSource", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity testSource(@Valid @RequestBody SourceTest sourceTest,
                                     @ApiIgnore BindingResult bindingResult,
                                     HttpServletRequest request) {

        if (bindingResult.hasErrors()) {
            ResultMap resultMap = new ResultMap().failAndRefreshToken(request).message(bindingResult.getFieldErrors().get(0).getDefaultMessage());
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        sourceService.testSource(sourceTest);
        return ResponseEntity.ok(new ResultMap().successAndRefreshToken(request));
    }

    /**
     * 释放重连
     *
     * @param dbBaseInfo
     * @param request
     * @return
     */
    @ApiOperation(value = "释放重连", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/reconnect", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity reconnect(@RequestBody DbBaseInfo dbBaseInfo,
                                    HttpServletRequest request) {
        sourceService.reconnect(dbBaseInfo.getSourceId(), dbBaseInfo);
        return ResponseEntity.ok(new ResultResponse().success());
    }

    /**
     * source 的数据库
     *
     * @param sourceId
     * @param request
     * @return
     */
    @ApiOperation(value = "getDbs")
    @GetMapping("/getDbs/databases")
    public ResponseEntity getSourceDbs(@PathVariable Long sourceId,
                                       HttpServletRequest request) {
        if (invalidId(sourceId)) {
            ResultMap resultMap = new ResultMap().failAndRefreshToken(request).message("Invalid source id");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        List<String> dbs = sourceService.getSourceDbs(sourceId);
        return ResponseEntity.ok(new ResultMap().successAndRefreshToken(request).payload(new SourceCatalogInfo(sourceId, dbs)));
    }


    /**
     * 获取source的数据库表
     *
     * @param sourceId
     * @param request
     * @return
     */
    @ApiOperation(value = "获取source的数据库表")
    @GetMapping("/getTables")
    public ResponseEntity getSourceTables(@RequestParam(name = "sourceId") Long sourceId,
                                          @RequestParam(name = "dbName") String dbName,
                                          HttpServletRequest request) {
        if (invalidId(sourceId)) {
            ResultMap resultMap = new ResultMap().failAndRefreshToken(request).message("Invalid source id");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        DBTables dbTables = sourceService.getSourceTables(sourceId, dbName);
        SourceDBInfo dbTableInfo = new SourceDBInfo();
        dbTableInfo.setSourceId(sourceId);
        BeanUtils.copyProperties(dbTables, dbTableInfo);
        return ResponseEntity.ok(new ResultMap().successAndRefreshToken(request).payload(dbTableInfo));
    }


    /**
     * 获取表里的所有字段
     *
     * @param sourceId
     * @param dbName
     * @param tableName
     * @param request
     * @return
     */
    @ApiOperation(value = "获取表里的所有字段")
    @GetMapping("/getColumns")
    public ResponseEntity getTableColumns(@RequestParam(name = "sourceId") Long sourceId,
                                          @RequestParam(name = "dbName") String dbName,
                                          @RequestParam(name = "tableName") String tableName,
                                          HttpServletRequest request) {
        if (invalidId(sourceId)) {
            ResultMap resultMap = new ResultMap().failAndRefreshToken(request).message("Invalid source id");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        if (StringUtils.isEmpty(tableName)) {
            ResultMap resultMap = new ResultMap().failAndRefreshToken(request).message("Table cannot be empty");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        TableInfo tableInfo = sourceService.getTableInfo(sourceId, dbName, tableName);

        SourceTableInfo sourceTableInfo = new SourceTableInfo();
        sourceTableInfo.setSourceId(sourceId);
        sourceTableInfo.setTableName(tableName);
        BeanUtils.copyProperties(tableInfo, sourceTableInfo);

        return ResponseEntity.ok(new ResultMap().successAndRefreshToken(request).payload(sourceTableInfo));
    }

}
